package com.future.util;

import com.future.cons.Const;
import com.future.mapper.OrderMapper;
import com.future.mapper.TradeMapper;
import com.future.vo.Stock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.function.Supplier;

/**
 * Description:
 *
 * @author weiruibai.vendor
 * Date: 2022/10/9 15:20
 */
@Service
public class CommSupplier<T> {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommSupplier.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    protected TradeMapper tradeMapper;

    public Stock select(int id) {
        return tradeMapper.select(id);
    }

    public T get(String key, Supplier<T> supplier) {
        Object oldTicketSum = redisTemplate.opsForValue().get(Const.TICKET_SUM);
        T data = null;
        int ticket;
        if (oldTicketSum == null || Integer.parseInt(oldTicketSum + "") < 1) {
            Stock stock = select(1);
            if (null != stock && stock.getStock() >= 1) {
                ticket = stock.getStock();
                redisTemplate.opsForValue().set(Const.TICKET_SUM, ticket);
            } else {
                LOGGER.error("票数为空，停止抢票");
                return data;
            }
        }
        try {
            data = supplier.get();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
        return data;
    }

}
